import { HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ProductAttributeCateServiceApi } from 'src/app/api/product-attribute-cate-api.service'
import { ProductAttributeCategory } from 'src/app/model/productAttr';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Router } from '@angular/router';



@Component({
  selector: 'app-product-attr',
  templateUrl: './product-attr.component.html',
  styleUrls: ['./product-attr.component.less', '../../../styles/container.css']
})
export class ProductAttrComponent implements OnInit {

  cateoryList: Array<ProductAttributeCategory> = new Array();
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  tableLoading = false;
  addModalVisible = false;
  addForm: FormGroup;
  editingId = -1;
  constructor(
    private fb: FormBuilder,
    private cateService: ProductAttributeCateServiceApi,
    private message: NzMessageService,
    private modal: NzModalService,
    private router: Router
  ) {
    this.addForm = this.fb.group({ name: [null, [Validators.required]] })
  }

  ngOnInit(): void {
    this.fetchListFromServer();
  }

  handleAdd() {
    this.addModalVisible = true;
  }

  handlePageIndexChange() {
    this.fetchListFromServer()
  }

  handlePageSizeChange() {
    this.fetchListFromServer()
  }

  handleUpdate(id: number, currentValue: string) {
    this.editingId = id;
    this.addForm.get('name').setValue(currentValue);
    this.addModalVisible = true;
  }

  handleDelete(id: number) {
    this.modal.confirm({
      nzTitle: '确定删除此商品类型？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.cateService.delete([id]).subscribe(
          respon => {
            this.message.success('删除成功');
            this.fetchListFromServer();
          },
          err => {
            this.message.error('删除错误')
          }
        )
      },
      nzCancelText: '取消',
      nzMaskClosable: true,
    })
  }

  handleAttribute(id: number, cateName: string) {
    this.routeToAttrList(id, cateName, 0);
  }

  handleParam(id: number, cateName: string) {
    this.routeToAttrList(id, cateName, 1);
  }

  handleAddModalCancel() {
    this.addForm.reset();
    this.addModalVisible = false;
    this.editingId = -1;
  }

  handleAddModalOk() {
    for (const key in this.addForm.controls) {
      this.addForm.controls[key].markAsDirty();
      this.addForm.controls[key].updateValueAndValidity();
    }
    if (this.addForm.valid) {
      if (this.editingId > 0) {
        this.updateCate();
      } else {
        this.createCate();
      }
    }
  }

  private routeToAttrList(cid: number, cname: string, type: number) {
    const url = this.router.parseUrl('/pms/productAttrList');
    url.queryParams = { 'cid': cid, 'cname': cname, 'type': type };
    this.router.navigateByUrl(url);
  }

  private createCate() {
    this.cateService.create({ name: this.addForm.get('name').value }).subscribe(
      item => {
        this.message.success('品牌创建成功');
        this.fetchListFromServer();
        setTimeout(() => {
          this.handleAddModalCancel();
        }, 500);
      },
      err => {
        console.log(err);
      }
    )
  }

  private updateCate() {
    this.cateService.update(this.editingId, { name: this.addForm.get('name').value }).subscribe(
      item => {
        this.message.success('品牌编辑成功');
        this.fetchListFromServer();
        setTimeout(() => {
          this.handleAddModalCancel();
        }, 500);
      },
      err => {
        console.log(err);
      }
    )
  }

  private fetchListFromServer() {
    this.tableLoading = true;
    let params = new HttpParams({
      fromObject: {
        'pageNum': this.pageIndex.toString(),
        'pageSize': this.pageSize.toString()
      }
    })
    this.cateService.list(params).subscribe(
      item => {
        this.tableLoading = false;
        this.cateoryList = item.list;
        this.total = item.total;
      },
      err => {
        this.tableLoading = false;
        console.error(err);
      }
    )
  }
}
